# -*- coding: utf-8 -*-
# @Time    : 2020/12/7 18:42
# @Author  : Guo_Zhanyu
# @File    : Gomoku_flask_BLACK_1.1.py
"""Imports"""
import sys
import requests
import datetime
import time
from Gomoku import *
from pygame.locals import *

# 服务器地址与端口号（默认值），后续可以输入
url = 'http://127.0.0.1:5000/'

# 获取的数据
board_dict_get = dict()

# 循环延时
time_delay = 0.05


class BoardOnline(Board):
    def __init__(self, lines):
        super(BoardOnline, self).__init__(lines)
        pass

    def drop(self, chessman, point):
        self._board[point.y][point.x] = chessman.value
        pass

    pass


def getBoardDictOnline():
    global board_dict_get

    # '/board' GET 得到board_dict_get
    r1 = requests.get(url + 'board')
    board_dict_get = eval(r1.text)
    # print(board_dict_get)
    pass


def postBoardDictOnline(x, y):
    board_dict_post = dict()
    board_dict_post['x'] = x
    board_dict_post['y'] = y
    # print(board_dict_post)
    # '/board' POST 提交board_dict
    r3 = requests.post(url + 'board', data=board_dict_post)
    print(str(datetime.datetime.now().strftime('%H:%M:%S')) + r3.text)
    pass


def main():
    global url

    ip = input("Input server's IP (Empty=default): ")
    if ip != '':
        url = 'http://' + ip + ':5000/'
        pass
    print('Connect with ' + url)

    pygame.init()
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    who_am_i = BLACK_CHESSMAN
    pygame.display.set_caption('Gomoku ' + who_am_i.name)
    font1 = pygame.font.SysFont('SimHei', 72)  # 黑体72
    font2 = pygame.font.SysFont('SimHei', 32)  # 黑体32
    f1width, f1height = font1.size('黑子获胜')
    f2width, f2height = font2.size('Press SPACE to continue...')

    board = BoardOnline(LINES)
    cur_runner = BLACK_CHESSMAN

    while True:
        # 获取数据，更新
        getBoardDictOnline()
        board.setBoard(board_dict_get['board'])
        runner = board_dict_get['runner']
        win = board_dict_get['win']

        if runner == 'black':
            cur_runner = BLACK_CHESSMAN
        elif runner == 'white':
            cur_runner = WHITE_CHESSMAN
            pass

        if win == 1:
            winner = BLACK_CHESSMAN
        elif win == 2:
            winner = WHITE_CHESSMAN
        else:
            winner = None
            pass

        for event in pygame.event.get():
            # “退出”事件
            if event.type == QUIT:
                # 重置服务器的棋盘
                postBoardDictOnline(-1, -1)
                sys.exit()
            elif event.type == KEYDOWN:
                # 空格按下
                if event.key == K_SPACE:
                    if winner is not None:
                        winner = None
                        cur_runner = BLACK_CHESSMAN
                        board = BoardOnline(LINES)
                        postBoardDictOnline(-1, -1)
                        pass
                    pass
                pass
            elif event.type == MOUSEBUTTONDOWN:
                if winner is None:
                    pressed_array = pygame.mouse.get_pressed(3)
                    # 左键按下
                    if pressed_array[0]:
                        if cur_runner.name == who_am_i.name:
                            mouse_pos = pygame.mouse.get_pos()
                            click_point = getClickPoint(mouse_pos)
                            if click_point is not None:
                                if board.canDrop(click_point):
                                    # 下子
                                    board.drop(cur_runner, click_point)
                                    cur_runner = getNextRunner(cur_runner)
                                    # 更新棋盘
                                    postBoardDictOnline(click_point.x, click_point.y)
                                    pass
                                pass
                            else:
                                print('超过棋盘范围...')
                                pass
                            pass
                        pass
                    pass
                pass
            pass

        # 画棋盘
        drawBoard(screen)
        # 画棋子
        drawStones(board, screen)

        # 结算界面
        if winner:
            print_text(screen, font1, (SCREEN_WIDTH - f1width)//2, (SCREEN_HEIGHT - f1height)//2 - f2height,
                       winner.name + '获胜', RED_COLOR)
            print_text(screen, font2, (SCREEN_WIDTH - f2width)//2, (SCREEN_HEIGHT - f1height)//2 + 2*f2height,
                       "Press SPACE to continue...", RED_COLOR)

        pygame.display.flip()
        time.sleep(time_delay)
        pass
    pass


if __name__ == '__main__':
    main()
    pass
